<template>
  <data-form :fields="fields" :model="model" />
</template>

<script setup>
  import DataForm from '@/components/DataForm'
  import ModelData from '@/common/classes/modelData';
  import { levelUnits } from '@/constant/units'
  import ci from '@/common/chartInstances'
  import useScanFormStore from '@/store/modules/form/scanForm'

  let renderer = null
  const fields = ref([
    {
      target: 'refLine',
      name: '参考线',
      isCheckbox: true,
    },
    {
      target: 'level',
      name: '电平',
      appendSelect: true,
      options: levelUnits
    },
  ])
  const model = reactive(new ModelData(fields.value, 'scan'))
  const scanFormStore = useScanFormStore()
  const findInstance = () => {
    const items = ci.get()
    const item = items.find(item => item.name === 'signalAnalyse')
    if (!item) {
      return null
    }
    if (!item.instance.redrawCb) {
      item.instance.redrawCb = () => addRefLine(item.instance)
    }
    return item.instance
  }

  watch(() => model.refLine, (val) => {
    if (val) {
      addRefLine(findInstance())
    } else {
      removeRefLine()
    }
  })
  watch(() => model.level.value, () => {
    if (model.refLine) {
      addRefLine(findInstance())
    }
  })
  const addRefLine = (instance) => {
    if (!instance) {
      return
    }
    renderer && renderer.destroy()
    const { plotLeft, plotTop, plotSizeX, plotSizeY } = instance
    const yLine = (plotSizeY / 10) * (scanFormStore.refLevel- model.level.value)/10 + plotTop
    const path = []
    path.push('M', plotLeft, yLine)
    path.push('L', plotLeft + plotSizeX, yLine)
    renderer = instance.renderer.path(path).attr({ stroke: '#009966', 'stroke-width': 1.5, zIndex: 12 }).add()
  }
  const removeRefLine = () => {
    renderer && renderer.destroy()
    renderer = null
  }
</script>
